// 设置时区为中国时区
process.env.TZ = "Asia/Shanghai";

import "reflect-metadata";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { WsAdapter } from "@nestjs/platform-ws";
import { DatabaseInitService } from "./services/database-init.service";
import { DatabaseSyncService } from "./services/database-sync.service";

// 确保 crypto 模块可用
if (typeof global.crypto === "undefined") {
  const crypto = require("crypto");
  global.crypto = crypto;
}

async function bootstrap(): Promise<void> {
  let app;

  try {
    console.log("🚀 开始启动应用...");

    // 打印环境变量信息（用于调试）
    console.log("🔧 环境变量配置:");
    console.log(`   DB_HOST: ${process.env.DB_HOST || "43.143.253.188"}`);
    console.log(`   DB_PORT: ${process.env.DB_PORT || "3306"}`);
    console.log(`   DB_USER: ${process.env.DB_USER || "nextjs"}`);
    console.log(`   DB_PASS: ${process.env.DB_PASS ? "***" : "未设置"}`);
    console.log(`   DB_NAME: ${process.env.DB_NAME || "nextjs"}`);
    console.log(`   PORT: ${process.env.PORT || "8206"}`);
    console.log(`   HOST: ${process.env.HOST || "0.0.0.0"}`);

    app = await NestFactory.create(AppModule);

    // 启用 CORS 以允许前端访问
    app.enableCors({ origin: true, credentials: true });
    app.useWebSocketAdapter(new WsAdapter(app));

    // 获取数据库服务并初始化数据库
    const databaseSyncService = app.get(DatabaseSyncService);
    const databaseInitService = app.get(DatabaseInitService);

    try {
      console.log("🔧 开始同步数据库结构...");
      await databaseSyncService.syncDatabase();
      console.log("✅ 数据库结构同步完成");

      console.log("🔧 开始初始化数据库...");
      await databaseInitService.initializeDatabase();
      console.log("✅ 数据库初始化完成");
    } catch (error) {
      console.error("❌ 数据库初始化失败:", error);
      // 继续启动应用，但记录错误
    }

    const port: number = parseInt(process.env.PORT || "3000", 10);
    const host: string = process.env.HOST || "0.0.0.0";

    await app.listen(port, host);
    const url = await app.getUrl();

    // 启动时打印访问地址和时区信息（可选，根据需要开启）
    console.log(`🚀 应用启动成功！`);
    console.log(`📡 服务地址: ${url}`);
    console.log(`🌍 时区设置: ${process.env.TZ}`);
    console.log(
      `⏰ 当前时间: ${new Date().toLocaleString("zh-CN", {
        timeZone: "Asia/Shanghai",
      })}`
    );
  } catch (error) {
    console.error("❌ 应用启动失败:", error);
    process.exit(1);
  }
}

bootstrap();
